package com.wili.c.asm;
import java.io.File;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import com.c.Ca;
import com.wili.c.Class9;
import com.wili.c.File9;
import com.wili.c.File9.TranverseFun;
import com.wili.c.Misc9;
import com.wili.c.Str9;
/**
 * 
 * @author weila 2021年3月7日
 */
public class Coms2b {

	/**
	 * 	从源码文件中删除自动插入的日志
	 */
	public static void removeLog_fromDirs() {
		File[] sourceDirs = FindPutFieldFromClassFile.SourceRootDirs;
		Ca.warn(1, "try removeLog_fromDirs:" + Misc9.strOfObjs("\n\t", sourceDirs));
		Map<Class<?>, List<PutFieldItem>> map = File9.readObject2(FindPutFieldFromClassFile.toFile, -1);
		Set<File> fSet = null;
		if (map != null) {
			fSet = new HashSet<>(map.size());
			for (Class<?> cls : map.keySet()) {
				cls = Class9.fileClassOf(cls);
				File javaFile = File9.javafileOf(null, cls, sourceDirs);
				if (javaFile == null)
					continue;
				fSet.add(javaFile);
			}
		}
		int[] times = { 0 };
		if (fSet != null) {
			for (File file : fSet) {
				if (removeLog_fromFile(file))
					++times[0];
			}
		}
		{
			for (File dir : sourceDirs) {
				File9.traverseFile(dir, 0, new TranverseFun() {
					@Override
					public void doFun(int depth, File file) {
						if (removeLog_fromFile(file))
							++times[0];
					}
				});
			}
		}
		if (times[0] == 0)
			Ca.warn(1, "\tLog not found.");
	}
	static Pattern RemovePat;
	static boolean removeLog_fromFile(File javaFile) {
		if ("".isEmpty() || RemovePat == null) {
			String st = FindPutFieldFromClassFile.InsertSt.replace("(", "\\(").replace(".", "\\.");
			st = st.replace("1,", "\\d+,") + "[^;]+;";
			st = "\\s+" + "(\\{\\s*" + st + "\\s*\\}|" + st + ")";
			RemovePat = Pattern.compile(st);
		}
		//_j.Logu.log(1, 3, "nl2", Str9.nl2);
		//File file = File9.javafileOf(null, cls, sourceDirs);
		if (javaFile.getName().equals("Batt.java"))
			Ca.pause();
		String fileSt = File9.strOfFile(javaFile);
		String fileSt2 = Str9.replaceAll(RemovePat, "", fileSt, 0);
		if (fileSt2.length() == fileSt.length())
			return false;
		Ca.warn(1, "removeLog from file: " + javaFile.getName());
		File9.str2file(fileSt2, javaFile, "", false);
		return true;
	}
}
